package com.xinghai.service.impl;


import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.domain.*;
import com.xinghai.mapper.JkqActivityLogMapper;
import com.xinghai.mapper.JkqActivityMapper;
import com.xinghai.mapper.JkqActivitySignMapper;
import com.xinghai.service.IJkqBadgeService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.xinghai.service.IJkqActivitySignService;

import javax.annotation.Resource;

/**
 * 活动报名记录Service业务层处理
 *
 * @author xinghai
 * @date 2025-08-02
 */
@Service
public class JkqActivitySignServiceImpl extends MPJBaseServiceImpl<JkqActivitySignMapper, JkqActivitySign>
        implements IJkqActivitySignService
{

    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Resource
    private JkqActivityMapper activityMapper;
    @Resource
    private JkqActivitySignMapper shareMapper;
    @Resource
    private JkqActivityLogMapper logMapper;
    @Autowired
    private IJkqBadgeService badgeService;
    /**
     * 查询活动报名记录列表
     *
     * @param jkqActivitySign 活动报名记录
     * @return 活动报名记录集合
     */
    @Override
    public List<JkqActivitySign> list(JkqActivitySign jkqActivitySign) {
        MPJLambdaWrapper<JkqActivitySign> query = new MPJLambdaWrapper<JkqActivitySign>()
                .setAlias("s")
                .selectAll(JkqActivitySign.class)
                .selectAs(JkqActivity::getTitle,JkqActivitySign::getTitle)
                .selectAs(JkqActivity::getImageUrl,JkqActivitySign::getImageUrl)
                .selectAs(JkqActivity::getType,JkqActivitySign::getType)
                .selectAs(JkqUser::getImageUrl,JkqActivitySign::getUserImage)
                .selectAs(JkqUser::getNickname,JkqActivitySign::getUserName)
                .selectAs(JkqUser::getHealthUserId,JkqUserBadge::getHealthUserId)
                .selectAs(JkqUserCopy::getNickname,JkqUserBadge::getHealthUserName)
                .leftJoin(JkqActivity.class, "a",JkqActivity::getId, JkqActivitySign::getActivityId)
                .leftJoin(JkqUser.class, "u",JkqUser::getId, JkqActivitySign::getUserId)
                .leftJoin(JkqUserCopy.class,"u2",JkqUserCopy::getId,JkqUser::getHealthUserId)
                .eq(jkqActivitySign.getActivityId()!= null,"s.activity_id", jkqActivitySign.getActivityId())
                .eq(jkqActivitySign.getUserId()!= null,"s.user_id", jkqActivitySign.getUserId())
                .eq(jkqActivitySign.getHealthUserId()!= null,"u.health_user_id", jkqActivitySign.getHealthUserId())
                .like(jkqActivitySign.getUserName()!= null  && !jkqActivitySign.getUserName().isEmpty(),"u.nickname", jkqActivitySign.getUserName())
                .like(jkqActivitySign.getName()!= null  && !jkqActivitySign.getName().isEmpty(),"s.name", jkqActivitySign.getName())
                .like(jkqActivitySign.getPhone()!= null  && !jkqActivitySign.getPhone().isEmpty(),"s.phone", jkqActivitySign.getPhone())
                .eq(jkqActivitySign.getStatus()!= null  && !jkqActivitySign.getStatus().isEmpty(),"s.status", jkqActivitySign.getStatus())
                .orderByDesc(JkqActivitySign::getUpdateTime);
        if (jkqActivitySign.getParams().get("beginCreateTime")!= null && !"".equals(jkqActivitySign.getParams().get("beginCreateTime"))
                &&jkqActivitySign.getParams().get("endCreateTime")!= null && !"".equals(jkqActivitySign.getParams().get("endCreateTime"))){
            query.between("s.create_time", jkqActivitySign.getParams().get("beginCreateTime"),jkqActivitySign.getParams().get("endCreateTime"));
        }
        if (jkqActivitySign.getParams().get("beginApplyTime")!= null && !"".equals(jkqActivitySign.getParams().get("beginApplyTime"))
                &&jkqActivitySign.getParams().get("endApplyTime")!= null && !"".equals(jkqActivitySign.getParams().get("endApplyTime"))){
            query.between("s.apply_time", jkqActivitySign.getParams().get("beginApplyTime"),jkqActivitySign.getParams().get("endApplyTime"));
        }
        return this.baseMapper.selectJoinList(JkqActivitySign.class,query);
    }

    /**
     * 导入活动报名记录信息
     *
     * @param list 活动报名记录信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<JkqActivitySign> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            JkqActivitySignMapper jkqActivitySignMapper = sqlSession.getMapper(JkqActivitySignMapper.class);
            list.forEach(jkqActivitySignMapper::insert);
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    @Override
    public boolean isSign(Long activityId, Long userId) {
        if (this.count(new QueryWrapper<JkqActivitySign>().eq("activity_id", activityId).eq("user_id", userId)) > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public void sign(JkqActivitySign jkqActivitySign) {
        this.baseMapper.insert(jkqActivitySign);
        activityMapper.updateSignNumById(jkqActivitySign.getActivityId());
        JkqActivityLog log = new JkqActivityLog();
        log.setActivityId(jkqActivitySign.getActivityId());
        log.setUserId(jkqActivitySign.getUserId());
        log.setName(jkqActivitySign.getUserName());
        log.setType(jkqActivitySign.getType());
        log.setImageUrl(jkqActivitySign.getUserImage());
        log.setYqUserId(jkqActivitySign.getYqUserId());
        if ("0".equals(jkqActivitySign.getType())){
            log.setRemark("参加了此活动");
        }else {
            log.setRemark("报名了此活动");
        }
        logMapper.insert(log);
        if (jkqActivitySign.getYqUserId() != null ){
            shareMapper.updateSignNumByActivityId(jkqActivitySign.getActivityId(),jkqActivitySign.getUserId());
        }
        //查看是否有获得的徽章
        BadgeItem badgeItem = new BadgeItem();
        badgeItem.setUserId(jkqActivitySign.getUserId());
        badgeItem.setType("3");
        badgeService.getBadgePower(badgeItem);
    }

    @Override
    public List<JkqActivitySign> getInfoByUserId(Long loginId,String status) {
        MPJLambdaWrapper<JkqActivitySign> query = new MPJLambdaWrapper<JkqActivitySign>()
                .selectAll(JkqActivitySign.class)
                .selectAs(JkqActivity::getTitle,JkqActivitySign::getTitle)
                .selectAs(JkqActivity::getImageUrl,JkqActivitySign::getImageUrl)
                .selectAs(JkqActivity::getType,JkqActivitySign::getType)
                .selectAs(JkqActivityAddress::getName,JkqActivitySign::getAddressName)
                .selectAs(JkqActivityAddress::getAddress,JkqActivitySign::getAddress)
                .selectAs(JkqActivityAddress::getLat,JkqActivitySign::getLat)
                .selectAs(JkqActivityAddress::getLng,JkqActivitySign::getLng)
                .leftJoin(JkqActivity.class, "a",JkqActivity::getId, JkqActivitySign::getActivityId)
                .leftJoin(JkqActivityAddress.class, "d",JkqActivityAddress::getId, JkqActivitySign::getAddressId)
                .eq(JkqActivitySign::getUserId, loginId)
                .eq(StringUtils.isNotBlank(status), JkqActivitySign::getStatus, status)
                .orderByDesc(JkqActivitySign::getCreateTime);
        return this.baseMapper.selectJoinList(JkqActivitySign.class,query);
    }

    @Override
    @Transactional
    public int updateInfoById(JkqActivitySign jkqActivitySign) {
        JkqActivitySign activitySign = baseMapper.selectById(jkqActivitySign.getId());
        if (activitySign==null){
            return 0;
        }
        if ("0".equals(activitySign.getStatus())){
            if ("1".equals(jkqActivitySign.getStatus())){
                activityMapper.updateGrantNumById(jkqActivitySign.getActivityId());
                baseMapper.updateById(jkqActivitySign);
                //查看是否有获得的徽章
                BadgeItem badgeItem = new BadgeItem();
                badgeItem.setUserId(jkqActivitySign.getUserId());
                badgeItem.setType("4");
                badgeService.getBadgePower(badgeItem);
                return 1;
            }
            return baseMapper.updateById(jkqActivitySign);
        }
        return 0;
    }
}
